/*  
 * @(#) SessionFilter.java Create on 2012-4-24 下午5:28:15   
 *   
 * Copyright 2012 by xl.   
 */

package com.doeis.core.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.doeis.common.Constant;
import com.doeis.manage.bean.User;
import com.doeis.manage.service.UserService;
import com.doeis.tools.DateHelper;


/**
 * 会话过滤器
 * @author wxy
 *
 */
@WebFilter(urlPatterns = "/*")
public class SessionFilter implements Filter {
	UserService userService = new UserService();
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		String uri = httpRequest.getRequestURI();
		if (uri.indexOf("/images") == 0 
				|| uri.indexOf("/static/") == 0 //脚本
				|| uri.indexOf("/index.jsp")==0 //跳转页面
				|| uri.equals("/")) //跳转页面
		{
			chain.doFilter(request, response);
			return;
		}

		Cookie[] cookie = httpRequest.getCookies();
		if(cookie!=null&&cookie.length>0){
			for (int i = 0; i < cookie.length; i++) {
				Cookie cook = cookie[i];
				if(cook.getName().equalsIgnoreCase("userCookie")){ //获取键 
					try {
						User user = userService.findByCookie(cook.getValue());
						if(user!=null){
							httpRequest.getSession().setAttribute(Constant.SYSTEM_CURRENT_USER, user);
							user.setCookie_token_expire(DateHelper.addTime(7));
							userService.update(user);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			} 
		}
		try {
			chain.doFilter(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			//ConnectionManage.getInstance().removeThreadLocalConnection();
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}
}
